package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    @Override
    public List<Menu> findLieBiao(String username) {
        List<Menu> list = menuDao.findMenu(username);
        for (Menu menu : list) {
            List<Menu> listImpl = menuDao.findMenuImpl(menu.getPath(),username);
            menu.setChildren(listImpl);
        }
        return list;
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Menu> page = menuDao.pageQuery();
        for (Menu menu : page) {
            if (menu.getLevel().equals("1")) {
                menu.setLevel("菜单");
            } else {
                menu.setLevel("功能");
            }
        }
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public void add(Menu menu) {
        //判断是否名称重复
        Menu menu1 = menuDao.findname(menu.getName());
        if (menu1 != null) {
            throw new RuntimeException("菜单或项目名称已存在");
        }
        //判断是否编码重复
        Menu menu2 = menuDao.findpath(menu.getPath());
        if (menu2 != null) {
            throw new RuntimeException("编码已存在");
        }
        menuDao.add(menu.getName(), menu.getPath(), menu.getIcon());
    }

    @Override
    public Menu findById(Integer id) {
        Menu menu = menuDao.findById(id);
        return menu;
    }

    @Override
    public void edit(Menu menu) {
        Menu menu1 = menuDao.findname(menu.getName());
        if (menu1 != null) {
            throw new RuntimeException("菜单或项目名称已存在");
        }
        Menu menu2 = menuDao.findpath(menu.getPath());
        if (menu2 != null) {
            throw new RuntimeException("编码已存在");
        }
        menuDao.edit(menu);
    }

    @Override
    public void delById(Integer id) {
        Menu menu = menuDao.findById(id);
        if (menu.getLevel().equals("1")) {
            menuDao.deleByIds(String.valueOf(menu.getPath()));
            menuDao.delById(id);
        } else {
            menuDao.delById(id);
        }
    }

}

